package net.zjitc.service.impl;

import net.zjitc.mapper.CartMapper;
import net.zjitc.mapper.ProductMapper;
import net.zjitc.pojo.Cart;
import net.zjitc.pojo.Product;
import net.zjitc.service.CartService;
import net.zjitc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/4/16 11:10
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;


    //查询当前用户的购物车条目，条目对应的商品信息

    @Override
    public List<Cart> findCartsByUid(Integer uid) {
        List<Cart> cartList = cartMapper.findProductsByUid(uid);
        for (Cart cart: cartList){
            Product product = productMapper.findById(cart.getPid());
            cart.setProduct(product);
        }
        return cartList;
    }

    @Override
    public int addProductToCart(Cart cart) {
        //添加购物车的时候，需要先判断下当前用户的购物车中是否已经存在此商品，
        // 如果存在，则只需要将原记录中的数量修改即可
        //如果不存在，才产生一条新的记录
        cart.setQuantity(1);
        cart.setChecked("0");
        //1.查询当前用户购物车情况
         Cart currentCart = cartMapper.findProductBelongToCurrentUser(cart.getPid(),cart.getUid());
         //2已经存在此商品的处理
         if (currentCart!= null){
             cart.setQuantity(cart.getQuantity()+currentCart.getQuantity());
            return  cartMapper.updateQuantity(cart);
         }
         //不存在的时候的处理
        cart.setCreate_time(new Date());
        return cartMapper.addNewProductToCart(cart);
    }

    @Override
    public int updateCart( Cart cart) {
        return cartMapper.updateQuantity(cart);
    }

    @Override
    public int deleteCart(Integer[] id) {
        return 0;
    }

    /**
     * 从购物车中删除当前商品条目
     * @param id
     * @return
     */
    @Override
    public int deleteCartItemById(Integer id) {
        return cartMapper.deleteItemById(id);
    }

    @Override
    public int deleteCartByUid(int id) {
        return cartMapper.deleteCartByUid(id);
    }
}
